using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Json;

namespace SmartMedical.WinUI
{
    /// <summary>
    /// 智慧医疗系统登录窗体 - 使用标准WinForms控件
    /// </summary>
    public partial class LoginForm : Form
    {
        #region 私有字段
        private Panel panelMain;
        private Label lblTitle;
        private Label lblUsername;
        private TextBox txtUsername;
        private Label lblPassword;
        private TextBox txtPassword;
        private Button btnLogin;
        private Button btnCancel;

        /// <summary>
        /// HTTP客户端，用于API调用
        /// </summary>
        private readonly HttpClient _httpClient;

        /// <summary>
        /// API基础URL - 读API端口（登录功能在读API中）
        /// </summary>
        private const string API_BASE_URL = "http://localhost:5043";
        #endregion

        #region 构造函数
        /// <summary>
        /// 初始化登录窗体
        /// </summary>
        public LoginForm()
        {
            InitializeComponent();
            InitializeLoginForm();

            // 初始化HTTP客户端
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(30);
        }
        #endregion

        #region 初始化方法
        /// <summary>
        /// 初始化登录窗体的基本设置
        /// </summary>
        private void InitializeLoginForm()
        {
            // 设置窗体属性
            this.Text = "智慧医疗系统 - 用户登录";
            this.Size = new Size(800, 600);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.Sizable;
            this.MaximizeBox = true;
            this.MinimizeBox = true;
            this.ShowInTaskbar = true;

            // 设置窗体图标（如果有的话）
            // this.Icon = Properties.Resources.AppIcon;

            // 设置默认按钮
            this.AcceptButton = btnLogin;
            this.CancelButton = btnCancel;
        }
        #endregion

        #region 事件处理方法
        /// <summary>
        /// 登录按钮点击事件
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private async void BtnLogin_Click(object sender, EventArgs e)
        {
            // 获取用户输入
            string username = txtUsername.Text.Trim();
            string password = txtPassword.Text.Trim();

            // 基本验证
            if (string.IsNullOrEmpty(username))
            {
                MessageBox.Show("请输入用户名！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtUsername.Focus();
                return;
            }

            if (string.IsNullOrEmpty(password))
            {
                MessageBox.Show("请输入密码！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPassword.Focus();
                return;
            }

            // 禁用登录按钮，防止重复点击
            btnLogin.Enabled = false;
            btnLogin.Text = "登录中...";

            try
            {
                // 调用登录API
                bool loginSuccess = await LoginAsync(username, password);

                if (loginSuccess)
                {
                    // 登录成功，显示主窗体
                    ShowMainForm();
                }
            }
            finally
            {
                // 恢复登录按钮状态
                btnLogin.Enabled = true;
                btnLogin.Text = "登录";
            }
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">事件参数</param>
        private void BtnCancel_Click(object sender, EventArgs e)
        {
            // 关闭应用程序
            Application.Exit();
        }

        /// <summary>
        /// 密码框按键事件（支持回车登录）
        /// </summary>
        /// <param name="sender">事件发送者</param>
        /// <param name="e">按键事件参数</param>
        private void TxtPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                BtnLogin_Click(sender, e);
            }
        }
        #endregion

        #region TODO: 待实现的方法
        /// <summary>
        /// 异步登录方法
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>登录结果</returns>
        private async Task<bool> LoginAsync(string username, string password)
        {
            try
            {
                // 发送GET请求到登录接口（使用查询参数）
                var response = await _httpClient.GetAsync($"{API_BASE_URL}/api/RBAC/Login?UserName={Uri.EscapeDataString(username)}&Password={Uri.EscapeDataString(password)}");

                if (response.IsSuccessStatusCode)
                {
                    // 解析响应内容
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var loginResponse = JsonConvert.DeserializeObject<LoginResponse>(responseContent);

                    if (loginResponse != null && loginResponse.Code == 200) // 根据后端APIResult结构判断成功
                    {
                        // 登录成功，保存用户信息
                        Properties.Settings.Default.UserToken = "temp_token"; // 后端暂时没有返回Token
                        Properties.Settings.Default.Username = loginResponse.Data?.UserName ?? "";
                        Properties.Settings.Default.DisplayName = loginResponse.Data?.UserName ?? "";
                        Properties.Settings.Default.UserRole = loginResponse.Data?.RoleName ?? "";
                        Properties.Settings.Default.Save();

                        MessageBox.Show($"登录成功！欢迎您，{loginResponse.Data?.UserName}", "登录成功", 
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return true;
                    }
                    else
                    {
                        MessageBox.Show(loginResponse?.Msg ?? "登录失败，请检查用户名和密码", "登录失败", 
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return false;
                    }
                }
                else
                {
                    MessageBox.Show($"登录请求失败：{response.StatusCode}", "网络错误", 
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show($"网络连接失败：{ex.Message}\n请检查网络连接或联系系统管理员",
                              "网络错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            catch (TaskCanceledException ex)
            {
                MessageBox.Show($"请求超时：{ex.Message}\n请稍后重试",
                              "超时错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"登录过程中发生错误：{ex.Message}",
                              "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        /// <summary>
        /// 显示主窗体（登录成功后调用）
        /// </summary>
        private void ShowMainForm()
        {
            try
            {
                // 创建并显示主窗体
                MainForm mainForm = new MainForm();
                mainForm.Show();

                // 隐藏登录窗体
                this.Hide();

                // 当主窗体关闭时，关闭整个应用程序
                mainForm.FormClosed += (s, e) => Application.Exit();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开主窗体时发生错误：{ex.Message}",
                              "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region 数据模型
        /// <summary>
        /// 登录请求模型
        /// </summary>
        public class LoginRequest
        {
            /// <summary>
            /// 用户名
            /// </summary>
            public string Username { get; set; } = string.Empty;

            /// <summary>
            /// 密码
            /// </summary>
            public string Password { get; set; } = string.Empty;
        }

        /// <summary>
        /// 登录响应数据模型（匹配后端APIResult结构）
        /// </summary>
        public class LoginResponse
        {
            /// <summary>
            /// 响应状态码（200表示成功）
            /// </summary>
            public int Code { get; set; }

            /// <summary>
            /// 响应消息
            /// </summary>
            public string Msg { get; set; } = string.Empty;

            /// <summary>
            /// 用户数据
            /// </summary>
            public UserDto? Data { get; set; }
        }

        /// <summary>
        /// 用户数据传输对象（匹配后端UserDto结构）
        /// </summary>
        public class UserDto
        {
            /// <summary>
            /// 用户ID
            /// </summary>
            public int Id { get; set; }

            /// <summary>
            /// 用户名
            /// </summary>
            public string UserName { get; set; } = string.Empty;

            /// <summary>
            /// 角色名称
            /// </summary>
            public string RoleName { get; set; } = string.Empty;

            /// <summary>
            /// 角色ID
            /// </summary>
            public int RoleId { get; set; }

            /// <summary>
            /// 是否启用
            /// </summary>
            public bool IsEnable { get; set; }
        }
        #endregion

        #region 窗体事件
        private void LoginForm_Load(object sender, EventArgs e)
        {

        }

        private void panelMain_Paint(object sender, PaintEventArgs e)
        {

        }

        /// <summary>
        /// 窗体关闭时释放HTTP客户端资源
        /// </summary>
        /// <param name="e">窗体关闭事件参数</param>
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            _httpClient?.Dispose();
            base.OnFormClosed(e);
        }
        #endregion
    }
}